package com.atguigu.tingshu.user.stragegy.impl;

import com.atguigu.tingshu.user.service.UserPaidTrackService;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.stragegy.UpdateUserPaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * UserPaidTrackStrategy 分集购买
 *
 * @author Petrichor
 * @version 2024/01/08 23:00
 **/
@Service
public class UserPaidTrackStrategy implements UpdateUserPaidRecordStrategy {
    private final UserPaidTrackMapper userPaidTrackMapper;
    private final TrackInfoFeignClient trackInfoFeignClient;
    private final UserPaidTrackService userPaidTrackService;
    @Autowired
    public UserPaidTrackStrategy(UserPaidTrackMapper userPaidTrackMapper, TrackInfoFeignClient trackInfoFeignClient, UserPaidTrackService userPaidTrackService) {
        this.userPaidTrackMapper = userPaidTrackMapper;
        this.trackInfoFeignClient = trackInfoFeignClient;
        this.userPaidTrackService = userPaidTrackService;
    }

    @Override
    public void updateUserPaidRecord(UserPaidRecordVo userPaidRecordVo) {
        // 先判断是否重新请求 查看数据库中是否存在相关数据
        String orderNo = userPaidRecordVo.getOrderNo();
        LambdaQueryWrapper<UserPaidTrack> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserPaidTrack::getOrderNo, orderNo);
        Long aLong = userPaidTrackMapper.selectCount(lambdaQueryWrapper);
        if (aLong != 0) {
            return;
        }

        // 根据声音id查询声音数据, 目的获取专辑id
        Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(userPaidRecordVo.getItemIdList().get(0));
        TrackInfo trackInfo = trackInfoResult.getData();

        // 获取购买的声音明细项数据, 构建保存交易记录对象
        List<UserPaidTrack> collect = userPaidRecordVo.getItemIdList().stream().map(itemId -> {
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidTrack.setUserId(userPaidRecordVo.getUserId());
            userPaidTrack.setAlbumId(trackInfo.getAlbumId());
            userPaidTrack.setTrackId(itemId);
            return userPaidTrack;
        }).collect(Collectors.toList());

        userPaidTrackService.saveBatch(collect);

    }

    @Override
    public String getItemType() {
        // 1002
        return SystemConstant.ORDER_ITEM_TYPE_TRACK;
    }
}


